<template>
  <div class="app-container">
<!--    {{this.$route.query}}-->
    {{ids}}{{totalAmount}}{{quantity}}
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="菜品名称" prop="menuName">
        <el-input
          v-model="queryParams.menuName"
          placeholder="请输入菜品名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="菜品价格" prop="menuPrice">
        <el-input
          v-model="queryParams.menuPrice"
          placeholder="请输入菜品价格"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="菜品类型" prop="menuTypeId">
        <el-input
          v-model="queryParams.menuTypeId"
          placeholder="请输入菜品类型"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="菜品数量" prop="menuCount">
        <el-input
          v-model="queryParams.menuCount"
          placeholder="请输入菜品数量"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="菜品图片" prop="menuLogo">
        <el-input
          v-model="queryParams.menuLogo"
          placeholder="请输入菜品图片"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="菜品更新时间" prop="menuLostTime">
        <el-date-picker clearable
          v-model="queryParams.menuLostTime"
          type="date"
          value-format="yyyy-MM-dd"
          placeholder="请选择菜品更新时间">
        </el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['menu:menu:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['menu:menu:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['menu:menu:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['menu:menu:export']"
        >导出</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-upload
          action
          :show-file-list="false"
          :auto-upload="false"
          :before-upload="beforeUpload"
          :on-change="uploadFile"
          style="display: inline-block;"
        >
          <Button icon="ios-download" type="primary">导入</Button>
        </el-upload>

      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    {{menuList}}
    <el-table v-loading="loading" :data="menuList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="ID" align="center" prop="id" />
      <el-table-column label="菜品名称" align="center" prop="menuName" />
      <el-table-column label="菜品价格" align="center" prop="menuPrice" />
      <el-table-column label="菜品类型" align="center" prop="menuTypeId" />
      <el-table-column label="菜品数量" align="center" prop="menuCount" />
      <el-table-column label="菜品图片" align="center" prop="menuLogo" />
      <el-table-column label="菜品更新时间" align="center" prop="menuLostTime" width="180">
        <el-table-column
          label="数量"
          width="200"
          prop="menuCount1">
          <template slot-scope="scope">
            <el-input-number @change="quantityChange()" v-model="scope.row.menuCount1" :min="1" :max="scope.row.menuCount" label="购买数量"></el-input-number>
          </template>
        </el-table-column>
<!--        <template slot-scope="scope">-->
<!--          <span>{{ parseTime(scope.row.menuLostTime, '{y}-{m}-{d}') }}</span>-->
<!--        </template>-->
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="success"
            icon="el-icon-edit"
            @click="ShoppingCart(scope.row)"
            v-hasPermi="['menu:menu:edit']"
          >加入购物车</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['menu:menu:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['menu:menu:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <el-button
      size="mini"
      type="success"
      @click="tocartList()"
    >去购物车</el-button>


    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />


    <!-- 添加或修改菜品对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="菜品名称" prop="menuName">
          <el-input v-model="form.menuName" placeholder="请输入菜品名称" />
        </el-form-item>
        <el-form-item label="菜品价格" prop="menuPrice">
          <el-input v-model="form.menuPrice" placeholder="请输入菜品价格" />
        </el-form-item>
        <el-form-item label="菜品类型" prop="menuTypeId">
          <el-input v-model="form.menuTypeId" placeholder="请输入菜品类型" />
        </el-form-item>
        <el-form-item label="菜品数量" prop="menuCount">
          <el-input v-model="form.menuCount" placeholder="请输入菜品数量" />
        </el-form-item>
        <el-form-item label="菜品图片" prop="menuLogo">
          <el-input v-model="form.menuLogo" placeholder="请输入菜品图片" />
        </el-form-item>
        <el-form-item label="菜品更新时间" prop="menuLostTime">
          <el-date-picker clearable
            v-model="form.menuLostTime"
            type="date"
            value-format="yyyy-MM-dd"
            placeholder="请选择菜品更新时间">
          </el-date-picker>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listMenu, getMenu, delMenu, addMenu, updateMenu ,importExport ,myshoppingcart,cartList} from "@/api/menu/menu";
export default {
  name: "Menu",
  data() {
    return {
      limitNum: 1,
      fileList: [],
      dialogVisible: false,
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 菜品表格数据
      menuList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        menuName: null,
        menuPrice: null,
        menuTypeId: null,
        menuCount: null,
        menuLogo: null,
        menuLostTime: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
      },
      totalAmount:0,
      multipleSelection:[],
      quantity:null
    };
  },
  created() {
    this.getList();
  },
  methods: {
    tocartList(){
      let tableId = this.$route.query.tableId;
      let userId = this.$route.query.userId
      const  business = {
        "tableId":tableId,
        "merchant":userId
      }
      this.$router.push({
        path: '/cuser/cartList',
        query: business
      })
    },

    quantityChange(){
      //数量改变 总金额清零
      this.totalAmount=0;
      this.multipleSelection.forEach((cart)=>{
        this.totalAmount = this.totalAmount + cart.menuPrice * cart.menuCount1;
      })
    },
    /** 查询菜品列表 */
    getList() {
      this.loading = true;
      listMenu(this.queryParams).then(response => {
        this.menuList = response.rows;
        this.menuList.forEach(menus=>{
          // menus.menuCount1=1;
          this.$set(menus,'menuCount1',1)
        })
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        menuName: null,
        menuPrice: null,
        menuTypeId: null,
        menuCount: null,
        menuLogo: null,
        menuLostTime: null,
        createTime: null,
        quantity:0
      };
      this.resetForm("form");
    },
    /** 加入购物车 */
    ShoppingCart(row) {
      debugger
      let tableId = this.$route.query.tableId;
      let userId = this.$route.query.userId
      const  tbMenu={
        "id":row.id,
        "menuName":row.menuName,
        "menuPrice":row.menuPrice,
        "menuCount":row.menuCount1,
        "couponId":row.couponId
      }
      myshoppingcart(tbMenu).then(res=>{
          if (res){
            console.log(res)
          }
      })
    },
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
      debugger
      //如果被选中
      this.totalAmount=0;
      //结果赋值
      this.multipleSelection = selection;
      //计算 总金额
      this.multipleSelection.forEach((cart)=>{
        this.totalAmount = this.totalAmount + cart.menuPrice * cart.menuCount;
      })
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加菜品";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      getMenu(id).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改菜品";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateMenu(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addMenu(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除菜品编号为"' + ids + '"的数据项？').then(function() {
        return delMenu(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('menu/menu/export', {
        ...this.queryParams
      }, `menu_${new Date().getTime()}.xlsx`)
    },

    handleClose(done) {
      this.$confirm('确认关闭？')
        .then(_ => {
          done();
        })
        .catch(_ => {});
    },
    beforeUpload(file) {
      console.log(file);
    },
    //导入信息
    uploadFile(file) {
      let _this = this;
      let fileName = file.name;
      let suffix = fileName.substring(fileName.lastIndexOf(".") + 1);
      console.log(file);
      if (suffix != "xls" && suffix != "xlsx") {
        this.$message.error("导入文件格式错误！请正确导入电子表格");
        return;
      }
      let formData = new FormData();
      formData.append("file", file.raw);
      try {
        importExport(formData)
      } catch (error) {
        console.error(error);
        let Msg = (error && error.message) || "";
        this.$message.error(Msg || "数据上传失败!");
      }
    },



  }
};
</script>
